package com.keter.common.domain.org;

import com.jfinal.aop.Aop;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.keter.framework.persist.base.BaseModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class Org extends BaseModel<Org> {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(Org.class);

    /*技术会员*/
    public final static String TYPE_TECHNICAL ="T";
    /*医疗会员*/
    public final static String TYPE_MEDICAL ="M";
    /*产业会员*/
    public final static String TYPE_INDUSTRY ="I";

    /*正常*/
    public final static String STATUS_NORMAL ="0";


    public static final Org dao = new Org();
//    public static final Org daox = Enhancer.enhance(Org.class);
    public static final Org daox = Aop.get(Org.class);

    @Override
    public List<Org> findAll() {
        return dao.find("select id,name,type,status,address from org");
    }


    public List<Org> findInIds(String ids) {
        String sql = " SELECT *  from org  WHERE id IN("+extractCommaStrToSqlIn(ids)+")";
        return dao.find(sql);
    }

    /**
     * 查询当前组织机构下的用户
     * @param orgId
     * @return
     */
    public List<Record> findUsers(String orgId) {
        String sql =
            " select u.id, u.username, u.name,u.email  " +
            " from user u,user_org o " +
            " where u.id = o.user_id and o.org_id = ?";
        return  Db.find(sql,orgId);
    }

    public boolean addUser(String orgId, String userId) {
        Record userOrg = new Record()
                .set("org_id", orgId)
                .set("user_id", userId);
        return Db.save("user_org", userOrg);
    }

    @Override
    public boolean save(){
        //设定一些故有逻辑
        return super.save();
    }

    @Before(Tx.class)
    public void saveTx(Org org1, Org org2){
        org1.save();
        int i =  1/0;
        org2.save();
    }

    public void saveTx2(Org org1, Org org2) {
        boolean tx = Db.tx(() -> {
            boolean r1 = org1.save();
            logger.info("r1:{}",r1);
            int i = 1 / 0;
            boolean r2 = org2.save();
            logger.info("r2:{}",r2);
            return false;
            });
        logger.info("tx:{}",tx);
    }

    @Override
    public void validate() {
        validator()
        .notEmpty("status")
        .notEmpty("type")
        .notEmpty("email")
        .length("name", 1,40)
        ;
    }
}